import logging
from logging.handlers import RotatingFileHandler

def setup_logging():
    """集中式日志配置"""
    # 主logger配置
    main_logger = logging.getLogger()
    main_logger.setLevel(logging.DEBUG)

    # 格式
    formatter = logging.Formatter(
        '%(asctime)s | %(name)-25s | %(levelname)-8s | %(message)s'
    )

    # 控制台输出
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)

    # 文件输出(按大小轮转)
    file_handler = RotatingFileHandler(
        'app.log', maxBytes=10*1024*1024, backupCount=5, encoding='utf-8'
    )
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)

    # 移除所有现有处理器
    for handler in main_logger.handlers[:]:
        main_logger.removeHandler(handler)

    # 添加处理器
    main_logger.addHandler(console_handler)
    main_logger.addHandler(file_handler)

# 应用配置
setup_logging()
